package com.lzyyj.gmis.base.webui.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;

import com.lzyyj.gmis.base.webui.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("serial")
public class AjaxInterceptor extends AbstractInterceptor {
	
	private static Log log = LogFactory.getLog(AjaxInterceptor.class);

	private boolean ajax = false;
	
	@Override
	public String intercept(ActionInvocation ai) throws Exception {

		Object obj = ai.getAction();
		if (obj instanceof BaseAction){
			ActionContext actionContext = ai.getInvocationContext();   
			HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);   
			ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

			BaseAction<?,?> action = (BaseAction<?,?>)obj;
			action.setAjax(ajax);
		}
		
		String result = ai.invoke();
		
		if (ajax){
			if (obj instanceof BaseAction){
				BaseAction<?,?> action = (BaseAction<?,?>)obj;
				if (ActionSupport.SUCCESS.equals(result)){
					action.getMapResult().put("success", true);
				}else{
					action.getMapResult().put("success", false);
				}
				if (action.getActionMessages().size()>0){
					action.getMapResult().put("message", action.getActionMessages().toString());
				}
				if (action.getActionErrors().size()>0){
					action.getMapResult().put("errorMessage", action.getActionErrors().toString());
				}
			}
			result = BaseAction.JSON;
		}
		return result;
	}
		
}